package common

import java.io.{ByteArrayInputStream, ByteArrayOutputStream, ObjectInputStream, ObjectOutputStream}

/**
  * 序列化工具
  */
object SerializationUtil {
  def serialize[T](t: T): Array[Byte] = {
    val bout = new ByteArrayOutputStream()
    val out = new ObjectOutputStream(bout)

    try {
      out.writeObject(t)
    } finally {
      if (out != null)
        out.close()
    }
    bout.toByteArray
  }

  def deserialize[T](data: Array[Byte]) = {
    val bin = new ByteArrayInputStream(data)
    val in = new ObjectInputStream(bin)

    val obj = try {
      in.readObject().asInstanceOf[T]
    } finally {
      if (in != null)
        in.close()
    }
    obj
  }
}
